/**
 * 根据 Axios Response 进行下载
 */
async function downloadAxiosResponse(axiosResponse) {
    const { headers, data: blob } = axiosResponse;
    const { 'content-disposition': disposition } = headers;

    const regExp = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
    const matcher = disposition?.match(regExp);
    const filename = matcher?.[1] ? decodeURIComponent(matcher[1].replace(/['"]/g, '')) : '';

    if ('msSaveOrOpenBlob' in window.navigator) {
        window.navigator.msSaveOrOpenBlob(blob, filename);
    } else {
        const anchor = document.createElement('a');
        const href = window.URL.createObjectURL(blob);

        anchor.download = filename;
        anchor.href = href;

        document.body.appendChild(anchor);
        anchor.click();

        document.body.removeChild(anchor);
        window.URL.revokeObjectURL(href);
    }
}

export default downloadAxiosResponse;
